var levelId = 0;
var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];
/*跳转到添加页面*/
function jumpToAdd(title, url) {
    levelId = 0;
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}

/*跳转到添加页面*/
function jumpToEdit(title, url) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}

// 查询分页数据
function initTable() {
    $.ajax({
        url:root.member.getLevelsByPage,
        cache: false,  //禁用缓存
        contentType: 'application/x-www-form-urlencoded',
        type: "post",
        data: {
            pageNum: 1,
            pageSize: 10,
            state:$("#state").val(),
            gradeName:$("#gradeName").val(),
        },
        success: function (data) {
            initTabls(data.data.result, 0);
            $('.M-box3').pagination({
                pageCount: data.data.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.member.getLevelsByPage,
                        cache: false,  //禁用缓存
                        contentType: 'application/x-www-form-urlencoded',
                        type: "post",
                        data: {
                            pageNum: api.getCurrent(),
                            pageSize: 10,
                            state:$("#state").val(),
                            gradeName:$("#gradeName").val(),
                        },
                        success: function (result) {
                            initTabls(result.data.result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}


// 渲染table
function initTabls(data) {
    sessionStorage.setItem("authorizedUsers", JSON.stringify(data));
    dataSource.splice(0,dataSource.length);//清空数组


        $.each(data, function (i, field) {
            var rowData = new Array();
            rowData.push(field.gradeName);
            rowData.push(field.moneyLowerLimit);
            rowData.push(field.moneyUpperLimit);
            rowData.push(field.gradeExplain);
            rowData.push(field.state);
            rowData.push(field.gradeId);
            rowData.push(field.index);
            rowData.push(field.gradeCoefficient);
            dataSource.push(rowData);

        });

    initDataTable(dataSource);

    function initDataTable(dataSource) {

        var dttable = $('#levelTable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#levelTable").DataTable({
            // "order": false,
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": false,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[6]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },


                {
                    "render": function (data, type, row, meta) {
                        var val = '商品实付额>=' + row[1];

                        return val;
                    },
                    "targets":2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[7]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if (row[4] == 10) {
                            val= '<span class="powerButton 443"><a id="state-' + row[5] + '" onclick="updateState(' + row[5] + ',' + row[4] + ',\''+row[0]+'\')">启用</a></span>';
                        } else {
                            val= '<span class="powerButton 443"><a id="state-' + row[5] + '" onclick="updateState(' + row[5] + ',' + row[4] + ',\''+row[0]+'\')">禁用</a></span>';
                        }
                        return val;
                    },
                    "targets":5
                },

                {
                    "render": function (data, type, row, meta) {
                        var val='';
                        val='<a class="powerButton 442" onclick="editLevel(' + row[5] + ')">修改</a>';
                        return val;
                    },
                    "targets":6
                }


            ]
        });
//权限控制函数
        power()
    };
}

// 禁用启用
function updateState(id, state,name) {
    var tostate = 0;
    if (state == 10) {
        tostate = 20;
    } else {
        tostate = 10;
    }
    $.ajax({
        url: root.member.updateLevelState,
        cache: false, //禁用缓存
        type: "post",
        jsonType: "json",
        data: {
            gradeId: id,
            state: tostate,
            gradeName:name
        },
        success: function (data) {
            if (data.errorCode == 0) {
                if (tostate == 10) {
                    $("#state-" + id).parent().html('<a id="state-' + id + '" onclick="updateState(' + id + ',10,'+name+')">启用</a> ');
                    initTable()
                } else {
                    $("#state-" + id).parent().html('<a id="state-' + id + '" onclick="updateState(' + id + ',20,'+name+')">禁用</a>');
                    initTable()
                }

            } else {
                layer.msg(data.sub_msg, {
                    icon: 2,
                    time: 3000
                });
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest);
            console.log(textStatus);
            console.log(errorThrown);
            console.log("!!!!会员等级系统异常!!!!");
            layer.msg('会员等级系统异常!', {
                icon: 2,
                time: 3000
            });
            layer.closeAll();
        }
    });
}

// 编辑等级
function editLevel(id) {
    levelId = id;
    jumpToEdit('修改等级', 'levelDetail.html')
}

/*
// 添加行号
function addIndex(data) {
    if (data.length > 0) {
        var pageNum = $("#pageNum").val();
        var start = (pageNum - 1) * 10;
        for (let i = 0; i < data.length; i++) {
            const datum = data[i];
            datum.index = i + start + 1;
        }
    }
}
*/

